package com.activemq.async;

import cn.hutool.core.date.DateUtil;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.AsyncCallback;

import javax.jms.*;
import java.util.UUID;

public class AsyncClusterProd {
    //加上jms.userAsync
    public static final String CLUSTER_URL = "failover:(tcp://wangweiye:61616,tcp://wangwy:61616,tcp://192.168.222.211:61616)?randomize=false&jms.useAsyncSend=true";
    public static final String QUEUE_NAME = "queue-cluster";

    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(CLUSTER_URL);
        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(QUEUE_NAME);
        ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);
        for (int i = 0; i < 3; i++) {
            TextMessage textMessage = session.createTextMessage("集群队列测试:" + DateUtil.now() + "+" + i);
            textMessage.setJMSMessageID(UUID.randomUUID().toString());
            String msgId = textMessage.getJMSMessageID();
            producer.send(textMessage, new AsyncCallback() {
                @Override
                public void onSuccess() {
                    System.out.println(msgId + "已经发送成功");
                }

                @Override
                public void onException(JMSException e) {
                    System.out.println(msgId + "异常" + e.getMessage());
                }
            });
            producer.send(textMessage);
        }
        producer.close();
        session.close();
        connection.close();
    }
}
